<template>
  <div>
    {{ loading ? "正在登录..." : "" }}
  </div>
</template>

<script setup>
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";

const route = useRoute();

onMounted(() => {
    login();
});

const loading = ref(false);
const error = ref(false);
const errorMessage = ref('');
    async function login() {
        const { code, e, isNative, origin } = route.query;
         const localOrgInfo = JSON.parse(
        localStorage.getItem("yxtlm_orgInfo") || '{"origin": ""}')
        loading.value = true;
        error.value = false;
        const domain = origin

        // 确定 API 环境
        let api_env = 'www';
        if (e.includes('tf')) {
          api_env = 'test';
        } else if (e.includes('di')) {
          api_env = 'dev';
        }
        const url = `https://${api_env}.x-mate.com/rest/learning/login`;

        try {
          // 使用 fetch 进行 POST 请求
          const response = await fetch(url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
            code,
              e,
               domain, // 或其他域名信息
              productCode: 'nova_guide',
            }),
          });

          // 处理响应
          const res = await response.json();
          if (res.code === 0) {
            handleSuccess(res);
          } else {
            handleError(res);
          }
        } catch (e) {
          console.error('请求失败:', e);
          errorMessage = '请求发生错误！';
          error.value = true;
        } finally {
          loading.value = false;
        }
    }

    function handleSuccess(res) {
        window.flutter_inappwebview.callHandler('ssoLogin', JSON.stringify(res));
    }

    function handleError(res) {
     ;
      this.errorMessage = '登录失败！';
      this.error = true;
    }

    function setStoreEveryKey(obj) {
      for (let key in obj) {
        let value = obj[key];
        // 如果 value 是对象，则转为 JSON 字符串
        if (typeof value === 'object') {
          value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
      }
    }
    function goBack() {
      const currentUrl = window.location.href;
      const loginUrl = currentUrl.split('?')[0].replace('thirdLogin.html', '');
      window.location.href = loginUrl;
    }
</script>

<style lang="less" scoped></style>
